package com.ipt.frm.pw;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public final class LoginServlets extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//Paramettros de inicio del Servlet
	static final String INIT_PARAM_USER_NAME = "username";
	static final String INIT_PARAM_USER_PASS = "userpass";
	//Parametros de la request de la jsp
	static final String LOGIN_JSP_PARAM_USER_NAME = "user";
	static final String LOGIN_JSP_PARAM_USER_PASS = "password";
	
	//Mensajes enviados por request para mostrar al usuario
	static final String MSG = "MSG";
	
	static Properties properties;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlets() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		
		
		//recoger valores de la request
		String loginUser = request.getParameter(LOGIN_JSP_PARAM_USER_NAME);
		String loginPass = request.getParameter(LOGIN_JSP_PARAM_USER_PASS);
		
		
		//compararlos 
		
		if(getInitParameter(INIT_PARAM_USER_NAME).equals(loginUser) && 
				getInitParameter(INIT_PARAM_USER_PASS).equals(loginPass)){
			//si validado guardar en ssession + index.jsp
			session.setAttribute(INIT_PARAM_USER_NAME, loginUser);
			session.setAttribute(INIT_PARAM_USER_PASS, loginPass);
			//forward index.jsp
			RequestDispatcher dispacher = this.getServletContext().getRequestDispatcher("/index.jsp");
			dispacher.forward(request, response);
			
		}
		else{
			//TODO meter estos literales en un fichero .properties
			//msg error
			Mensaje mensaje;
			properties = new Properties();
    		properties = (Properties) getServletContext().getAttribute("propiedad");
			mensaje = new Mensaje(TipoMensaje.ERROR,properties.getProperty("login.error"));
    		//forward
    		request.setAttribute("MSG", mensaje);
			
			//si no validado login.jsp + mseg error
			RequestDispatcher dispacher = this.getServletContext().getRequestDispatcher("/login.jsp");
			dispacher.forward(request, response);
		}
				
	
	}

}
